package com.tyylab.message.event.publish.remote.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Preconditions;
import com.tyylab.message.api.event.ITyylabEventPublisher;
import com.tyylab.message.api.event.model.ITyylabUniqueEvent;
import com.tyylab.message.api.event.model.ITyylabEvent;
import com.tyylab.message.core.model.TransMessage;
import com.tyylab.message.core.service.ISyncPublish;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Slf4j
@Service
public class RemoteEventPublisher implements ITyylabEventPublisher {
    @Autowired
    ISyncPublish publish;

    @Override
    public void publish(ITyylabEvent event) {
        Preconditions.checkNotNull(event);
        if (event instanceof ITyylabUniqueEvent){
            if (null!= ((ITyylabUniqueEvent) event).getIsUnique()
                    && ((ITyylabUniqueEvent) event).getIsUnique() >0
                    && StringUtils.isBlank(((ITyylabUniqueEvent) event).getHash())){
                ((ITyylabUniqueEvent) event).setHash(event.hashCode()+"");
            }
        }
        String json = JSON.toJSONString(event);
        JSONObject jsonObject =JSONObject.parseObject(json);
        TransMessage simulMessage = TransMessage.builder()
                .message(jsonObject)
                .clz(event.getClass().getName())
                .id(generateUUID())
                .build();
        String msgJson =JSON.toJSONString(simulMessage);
        log.info("publish event :" + msgJson);
        publish.publish(simulMessage);
        log.info("publish event success :" + msgJson);
    }

    static String generateUUID() {
        UUID uuid = UUID.randomUUID();
        return uuid.toString().replaceAll("-","");
    }
}
